package public

import (
	"gitee.com/kinwyb/conv"
	"math"
	"math/rand"
	"strconv"
	"strings"
	"sync"
	"time"
)

type IDGenerator interface {
	// Next 生成下一个ID序列
	Next() uint64
}

type idGenerator struct {
	memberID   uint16
	unixSecond int64
	generator  *etcdIDGenerator
}

func (i *idGenerator) Next() uint64 {
	now := time.Now()
	if now.Unix() != i.unixSecond {
		i.unixSecond = now.Unix()
		i.generator = NewEtcdIDGenerator(i.memberID, now)
	}
	return i.generator.Next()
}

func NewGenerator(memberID uint16, now time.Time) IDGenerator {
	return &idGenerator{
		memberID:   memberID,
		unixSecond: now.Unix(),
		generator:  NewEtcdIDGenerator(memberID, now),
	}
}

const (
	tsLen     = 5 * 8
	cntLen    = 8
	suffixLen = tsLen + cntLen
)

// EtcdIDGenerator generates unique identifiers based on counters, timestamps, and
// a node member ID.
//
// The initial id is in this format:
// High order 2 bytes are from memberID, next 5 bytes are from timestamp,
// and low order one byte is a counter.
// | prefix   | suffix              |
// | 2 bytes  | 5 bytes   | 1 byte  |
// | memberID | timestamp | cnt     |
//
// The timestamp 5 bytes is different when the machine is restart
// after 1 ms and before 35 years.
//
// It increases suffix to generate the next id.
// The count field may overflow to timestamp field, which is intentional.
// It helps to extend the event window to 2^56. This doesn't break that
// id generated after restart is unique because etcd throughput is <<
// 256req/ms(250k reqs/second).
type etcdIDGenerator struct {
	mu sync.Mutex
	// high order 2 bytes
	prefix uint64
	// low order 6 bytes
	suffix uint64
}

func NewEtcdIDGenerator(memberID uint16, now time.Time) *etcdIDGenerator {
	prefix := uint64(memberID) << suffixLen
	unixMilli := uint64(now.UnixNano()) / uint64(time.Millisecond/time.Nanosecond)
	suffix := lowbit(unixMilli, tsLen) << cntLen
	return &etcdIDGenerator{
		prefix: prefix,
		suffix: suffix,
	}
}

// Next generates a id that is unique.
func (g *etcdIDGenerator) Next() uint64 {
	g.mu.Lock()
	defer g.mu.Unlock()
	g.suffix++
	id := g.prefix | lowbit(g.suffix, suffixLen)
	return id
}

func lowbit(x uint64, n uint) uint64 {
	return x & (math.MaxUint64 >> (64 - n))
}

var idGen = NewGenerator(uint16(rand.Uint32()>>16), time.Now())

// IDGen id生成器
func IDGen() string {
	id := idGen.Next()
	return strings.ToUpper(strconv.FormatUint(id, 32))
}

// IDGenUInt64 id生成
func IDGenUInt64() uint64 {
	return idGen.Next()
}

// IDGenIntString 整数型ID
func IDGenIntString() string {
	return conv.ToString(idGen.Next())
}
